import os
from datetime import datetime

from PyQt5.QtWidgets import (
    QWidget, QVBoxLayout, QHBoxLayout, QTableWidget, QTableWidgetItem,
    QHeaderView, QComboBox, QDateEdit, QPushButton, QLabel, QGroupBox,
    QMessageBox, QFrame, QTabWidget, QFileDialog, QGridLayout
)
from PyQt5.QtCore import Qt, QDate
from PyQt5.QtGui import QFont, QIcon
import logging
from bank_manage_system.admin.report_manager import ReportManager

logger = logging.getLogger(__name__)

class ReportTab(QWidget):
    def __init__(self, db, user_id="admin"):
        super().__init__()
        self.db = db
        self.user_id = user_id
        self.report_manager = ReportManager(db, user_id)
        self.initUI()
        self.apply_styles()

    def initUI(self):
        main_layout = QVBoxLayout()
        main_layout.setSpacing(15)
        main_layout.setContentsMargins(20, 15, 20, 20)

        # 标题栏
        header_layout = QHBoxLayout()
        title_label = QLabel("银行管理系统 - 管理员面板")
        title_label.setFont(QFont("Microsoft YaHei UI", 14, QFont.Bold))
        header_layout.addWidget(title_label, 0, Qt.AlignLeft)

        # 管理员信息
        header_layout.addStretch()
        admin_layout = QHBoxLayout()
        admin_label = QLabel("管理员 ID:")
        admin_label.setFont(QFont("Microsoft YaHei UI", 10))
        admin_id_label = QLabel(self.user_id)
        admin_id_label.setFont(QFont("Microsoft YaHei UI", 10, QFont.Bold))
        admin_id_label.setStyleSheet("background-color: rgba(231, 76, 60, 30); padding: 5px; border-radius: 4px;")
        admin_layout.addWidget(admin_label)
        admin_layout.addWidget(admin_id_label)
        header_layout.addLayout(admin_layout)
        main_layout.addLayout(header_layout)

        # 分隔线
        separator = QFrame()
        separator.setFrameShape(QFrame.HLine)
        separator.setStyleSheet("background-color: #a0a0a0; height: 2px;")
        main_layout.addWidget(separator)

        # 报表参数区域
        report_group = QGroupBox("报表参数")
        report_layout = QGridLayout()
        report_layout.setHorizontalSpacing(15)
        report_layout.setVerticalSpacing(10)

        # 报表类型
        report_layout.addWidget(QLabel("报表类型:"), 0, 0)
        self.report_type = QComboBox()
        self.report_type.addItems([
            "交易流水报表",
            "客户账户汇总",
            "存款类型分布",
            "挂失记录报表",
            "月度交易统计"
        ])
        report_layout.addWidget(self.report_type, 0, 1)

        # 时间范围
        report_layout.addWidget(QLabel("时间范围:"), 1, 0)
        time_layout = QHBoxLayout()
        self.date_start = QDateEdit(QDate.currentDate().addMonths(-1))
        self.date_start.setCalendarPopup(True)
        self.date_start.setDisplayFormat("yyyy/MM/dd")
        self.date_end = QDateEdit(QDate.currentDate())
        self.date_end.setCalendarPopup(True)
        self.date_end.setDisplayFormat("yyyy/MM/dd")
        time_layout.addWidget(self.date_start)
        time_layout.addWidget(QLabel("至"))
        time_layout.addWidget(self.date_end)
        report_layout.addLayout(time_layout, 1, 1)

        # 生成报表按钮
        self.generate_btn = QPushButton("生成报表")
        self.generate_btn.clicked.connect(self.generate_report)
        self.generate_btn.setMinimumWidth(120)
        report_layout.addWidget(self.generate_btn, 1, 2)

        # 导出报表部分
        export_layout = QHBoxLayout()
        export_layout.setContentsMargins(0, 0, 0, 0)
        export_layout.setSpacing(8)

        # 导出图标
        export_icon = QLabel()
        export_icon.setPixmap(QIcon(":bank_manage_system/export.png.png").pixmap(24, 24))
        export_icon.setStyleSheet("background: transparent; padding-right: 5px;")
        export_layout.addWidget(export_icon)

        # 导出按钮
        self.export_btn = QPushButton("导出报表")
        self.export_btn.clicked.connect(self.export_csv)
        self.export_btn.setMinimumWidth(120)
        self.export_btn.setEnabled(False)
        export_layout.addWidget(self.export_btn)

        # 添加到报表布局
        report_layout.addLayout(export_layout, 1, 3)

        report_group.setLayout(report_layout)
        main_layout.addWidget(report_group)

        # 报表表格区域
        self.table = QTableWidget()
        self.table.setColumnCount(8)
        self.table.setHorizontalHeaderLabels([
            "交易ID", "卡号", "客户姓名",
            "交易时间", "交易类型", "金额", "对方卡号", "备注"
        ])

        # 设置表头样式
        header = self.table.horizontalHeader()
        header.setSectionResizeMode(QHeaderView.Interactive)
        header.setStretchLastSection(True)
        header_font = self.table.font()
        header_font.setBold(True)
        header.setFont(header_font)

        self.table.setEditTriggers(QTableWidget.NoEditTriggers)
        self.table.setSelectionBehavior(QTableWidget.SelectRows)
        self.table.setSelectionMode(QTableWidget.SingleSelection)
        self.table.setSortingEnabled(True)
        self.table.setColumnWidth(3, 180)

        main_layout.addWidget(self.table)
        self.setLayout(main_layout)

    def apply_styles(self):
        self.setStyleSheet("""
            QGroupBox {
                border: 1px solid #3498db;
                border-radius: 8px;
                margin-top: 1.5em;
                padding: 10px;
                font-weight: bold;
            }
            QGroupBox::title {
                subcontrol-origin: margin;
                left: 10px;
                padding: 0 5px;
            }
            QPushButton {
                background-color: #3498db;
                color: white;
                border-radius: 4px;
                padding: 8px 16px;
                font-weight: bold;
            }
            QPushButton:hover {
                background-color: #2980b9;
            }
            QPushButton:disabled {
                background-color: #bdc3c7;
            }
            QTabWidget::pane {
                border: 1px solid #3498db;
                border-radius: 8px;
            }
            QTabBar::tab {
                background: #f0f0f0;
                border: 1px solid #bdc3c7;
                padding: 8px 15px;
                border-top-left-radius: 5px;
                border-top-right-radius: 5px;
                margin-right: 2px;
            }
            QTabBar::tab:selected {
                background: #3498db;
                color: white;
                border-bottom-color: #3498db;
            }
            QTableWidget {
                gridline-color: #e0e0e0;
                alternate-background-color: #f8f9fa;
            }
            QHeaderView::section {
                background-color: #3498db;
                color: white;
                padding: 4px;
            }
        """)
        self.table.setAlternatingRowColors(True)

    def generate_report(self):
        report_type = self.report_type.currentText()
        start_date = self.date_start.date().toString("yyyy-MM-dd")
        end_date = self.date_end.date().toString("yyyy-MM-dd")

        logger.info(f"{self.user_id} 生成报表: {report_type}, 时间范围: {start_date} 至 {end_date}")

        try:
            if report_type == "交易流水报表":
                headers, data = self.report_manager.generate_transaction_report(start_date, end_date)
            elif report_type == "客户账户汇总":
                headers, data = self.report_manager.generate_customer_summary_report()
            elif report_type == "存款类型分布":
                headers, data = self.report_manager.generate_deposit_distribution()
            elif report_type == "挂失记录报表":
                headers, data = self.report_manager.generate_loss_report(start_date, end_date)
            elif report_type == "月度交易统计":
                headers, data = self.report_manager.generate_monthly_statistics()

            self.report_manager.current_report_data = data
            self.report_manager.current_headers = headers
            self.report_manager.current_report_type = report_type
            self.display_data_in_table(headers, data, "当前时间范围内没有数据")
            self.export_btn.setEnabled(True)

        except Exception as e:
            logger.error(f"生成报表出错: {str(e)}")
            QMessageBox.critical(self, "生成报表错误", f"数据库查询失败: {str(e)}")

    def display_data_in_table(self, headers, data, empty_message="没有找到数据"):
        self.table.clear()
        self.table.setColumnCount(len(headers))
        self.table.setHorizontalHeaderLabels(headers)

        if data:
            self.table.setRowCount(len(data))

            for row_idx, row in enumerate(data):
                for col_idx, value in enumerate(row):
                    if isinstance(value, float):
                        display_value = f"{value:,.2f}"
                    elif value is None:
                        display_value = ""
                    else:
                        display_value = str(value)

                    item = QTableWidgetItem(display_value)

                    if isinstance(value, (int, float)):
                        item.setTextAlignment(Qt.AlignRight | Qt.AlignVCenter)
                    else:
                        item.setTextAlignment(Qt.AlignCenter)

                    self.table.setItem(row_idx, col_idx, item)

            self.table.resizeColumnsToContents()
            self.table.setAlternatingRowColors(True)
        else:
            self.table.setRowCount(1)
            self.table.setColumnCount(1)
            item = QTableWidgetItem(empty_message)
            item.setTextAlignment(Qt.AlignCenter)
            self.table.setItem(0, 0, item)
            self.table.horizontalHeader().setSectionResizeMode(0, QHeaderView.Stretch)

    def export_csv(self):
        if not self.report_manager.current_report_data:
            QMessageBox.warning(self, "导出失败", "没有可导出的报表数据")
            return

        options = QFileDialog.Options()

        default_file_name = f"{self.report_manager.current_report_type}_{datetime.now().strftime('%Y%m%d_%H%M%S')}.csv"
        file_path, _ = QFileDialog.getSaveFileName(
            self,
            "导出报表",
            default_file_name,
            "CSV文件 (*.csv);;所有文件 (*)",
            options=options
        )

        if not file_path:
            return

        if not file_path.lower().endswith('.csv'):
            file_path += '.csv'

        success, result = self.report_manager.export_csv(file_path)

        if success:
            QMessageBox.information(
                self,
                "导出成功",
                f"{self.report_manager.current_report_type}已成功导出为CSV文件\n\n保存位置: {file_path}",
                QMessageBox.Ok
            )
            self.open_export_folder(os.path.dirname(file_path))
        else:
            QMessageBox.critical(
                self,
                "导出失败",
                f"导出报表时发生错误:\n{result}"
            )

    def open_export_folder(self, folder_path):
        try:
            import platform
            import subprocess
            system = platform.system()

            if system == "Windows":
                os.startfile(folder_path)
            elif system == "Darwin":
                subprocess.Popen(["open", folder_path])
            elif system == "Linux":
                subprocess.Popen(["xdg-open", folder_path])
        except Exception as e:
            logger.warning(f"打开导出文件夹失败: {str(e)}")